package me.leiusual.sharing.ui.setting

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.tencent.bugly.beta.Beta
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_setting_home.*
import me.leiusual.sharing.BuildConfig
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class SettingHomeFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: SettingHomeViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_setting_home, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_modify_password.setOnClickListener {
      findNavController().navigate(R.id.action_settingHomeFragment_to_settingPasswordFragment)
    }

    text_view_about.setOnClickListener {
      findNavController().navigate(R.id.action_settingHomeFragment_to_settingAboutFragment)
    }

    text_view_clean.setOnClickListener {
      viewModel.clearCache()
    }

    text_view_update.setOnClickListener {
      Beta.checkUpgrade(true, false)
    }

    text_view_contact.setOnClickListener(this)

    button_exit.setOnClickListener {
      showExitDialog()
    }

    bindData()

    observeData()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_contact -> {
        findNavController().navigate(R.id.action_settingHomeFragment_to_settingContactFragment)
      }
    }
  }

  private fun bindData() {
    text_view_update_value.text = "v${BuildConfig.VERSION_NAME}"
  }

  private fun observeData() {
    viewModel.clearCache.observe(viewLifecycleOwner, HandleObserver<Data<Unit>> {
      Timber.v("clearCache = %s", it)
      when (it) {
        is Data.Loading -> {
        }
        is Data.Error -> {
        }
        is Data.Success -> {
          toast("已清理")
        }
      }
    })
  }

  private fun showExitDialog() {
    AlertDialog.Builder(requireContext())
        .setMessage("退出账号？")
        .setPositiveButton("确认") { _, _ ->
          viewModel.token.clear()
          findNavController().popBackStack()
        }
        .setNegativeButton("取消", null)
        .show()
  }
}